home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c++-part1 / 4674 < prev    next >
Encoding:
Text File  |  1996-08-06  |  2.0 KB  |  65 lines

  1. Path: cnn.exu.ericsson.se!news
  2. From: ebumow@ebu.ericsson.com (Mickey Williams 66753)
  3. Newsgroups: comp.lang.c++
  4. Subject: Re: How to handle error in constructor
  5. Date: 31 Jan 1996 16:51:50 GMT
  6. Organization: Ericsson Inc.
  7. Distribution: world
  8. Message-ID: <4eo6n6$rbp@cnn.exu.ericsson.se>
  9. References: <DLyyIM.5EG@teslab.lab.oz.au>
  10. Reply-To: ebumow@ebu.ericsson.com
  11. NNTP-Posting-Host: franklin.ebu.ericsson.se
  12.  
  13. In article 5EG@teslab.lab.oz.au,  andrew@teslab.lab.oz.au (Andrew Phillips) writes:
  14. >I'm converting and enhancing a simple program in C to C++.  Without going
  15. >into too much detail I have a class that represents a file on disk.  The
  16. >contructor opens the file, but what should it do if the file cannot be
  17. >opened?  The C program just calls fopen() tests the return value and 
  18. >if there's an error it prints a message and exits.
  19.  
  20. >In C++ I thought to set a flag in the constructor and have a member function
  21. >that tests the flag to see if the file was opened correctly.
  22.  
  23. In practice, it is impossible to ensure that this works as intended. Also,
  24. every user of this class must understand this error handling mechanism. On
  25. the other hand, exceptions are part of the standard, so throwing one of
  26. the standard exceptions should be much safer.
  27.  
  28. > This seems
  29. >rather inelegant -- I guess exceptions would be the elegant way but seem
  30. >like overkill for such a simple program.
  31.  
  32. Elegant, schmelegant. It's the correct tool for the job.
  33.  
  34. class CMyFile {
  35.     //insert useful code here
  36. };
  37.  
  38. main()
  39. {
  40.     try
  41.     {
  42.        CMyFile   theFile( "filename" );
  43.  
  44.        // remaining work
  45.  
  46.     }
  47.     catch( /*pick an exception type*/ )
  48.     {
  49.         cout << "Your message here" << endl;
  50.     }
  51. }
  52.  
  53. > I've looked in several C++ books but
  54. >error handling is given scant coverage except for exception handling.
  55.  
  56. That's because exception handling is the way to handle errors using
  57. C++ nowadays.
  58.  
  59. ------
  60.  Mickey Williams
  61.  Author of: - Essential Visual C++ 4
  62.             - Develop a Professional Visual C++ Application in 21 Days
  63.  
  64.  
  65.